import React from 'react';
import {
  View,
  ScrollView,
  TouchableOpacity,
  Platform,
  Alert,
} from 'react-native';
import {Text, Button, ListItem} from '@rneui/base';
import {
  useMap,
  useMount,
  useSafeState,
  useSetState,
  useUpdateEffect,
  useDebounceEffect,
} from 'ahooks';
import {round} from 'lodash';
import style from './style.less';
import {
  requestMultiple,
  checkMultiple,
  PERMISSIONS,
  RESULTS,
  openSettings,
  request,
} from 'react-native-permissions';
import {useNavigation} from '@react-navigation/native';
import {MapPowerResult, MapPowerName} from '@/config/power';
import dayjs from 'dayjs';
import {useSelector, useDispatch} from 'react-redux';

export {default as config} from "./config";
export default () => {
  const navigation = useNavigation();
  const appRunState = useSelector(state => state.appRunState.value);

  const [map, {setAll}] = useMap();
  const [group, setGropu] = useSafeState([]);


  const setInfo = async () => {
    const newMap = new Map();
    // for (const [name, key] of Object.entries(PERMISSIONS.ANDROID)) {
    //   newMap.set(key, {name: name});
    // }

    for (const [name] of MapPowerName) {
      const key = PERMISSIONS.ANDROID[name];
      newMap.set(key, {name: name});
    }

    const powerList = [...newMap].map(([key]) => key);
    try {
      const statuses = await checkMultiple(powerList);
      for (const [key, powerStr] of Object.entries(statuses)) {
        const oldData = newMap.get(key);
        newMap.set(key, {...oldData, powerStr});
      }
      setAll(newMap);

      const gArr = [
        RESULTS.GRANTED,
        RESULTS.LIMITED,
        RESULTS.DENIED,
        RESULTS.BLOCKED,
      ];
      const rtArr = [];
      gArr.forEach(targetValue => {
        const items = [];
        [...newMap].filter(([, item]) => {
          if (item.powerStr === targetValue) {
            items.push(item);
          }
        });
        rtArr.push(items);
      });

      setGropu(rtArr);

      // const gArr = [RESULTS.RESULTS.GRANTED]
    } catch (e) {
      console.log('获取权限异常', e.message);
    }
  };
  useMount(() => {
    setInfo();
    navigation.setOptions({
      headerRight: () => (
        <Button
          title="Open OS"
          onPress={() => {
            openSettings();
          }}
          size="sm"
        />
      ),
    });
  });

  useDebounceEffect(
    () => {
      if (appRunState === 'active') {
        setInfo();
      }
    },
    [appRunState],
    {wait: 0},
  );
  return (
    <ScrollView style={style.box}>
      {group.map((gRows, gIndex) => (
        <View key={gIndex} style={style.group}>
          {[...gRows].map((item, index) => (
            <ListItem key={index} style={{marginTop: 1}}>
              <ListItem.Content>
                <ListItem.Title>{MapPowerName.get(item.name)}</ListItem.Title>
                <Text style={style.remark}>{item.name}</Text>
              </ListItem.Content>
              <TouchableOpacity
                onPress={async () => {
                  if (
                    [RESULTS.UNAVAILABLE, RESULTS.GRANTED].includes(
                      item.powerStr,
                    )
                  ) {
                    return;
                  }
                  let v = '';
                  let t1 = dayjs();
                  let t2;
                  try {
                    v = await request(PERMISSIONS.ANDROID[item.name]);
                    t2 = dayjs();
                  } catch (e) {
                    Alert.alert('操作失败', e.message);
                    return;
                  }
                  let useMs = t2.diff(t1, 'ms');
                  if (useMs < 300 && v !== RESULTS.GRANTED) {
                    openSettings().catch(() =>
                      Alert.alert('操作失败', '打开系统设置'),
                    );
                  } else {
                    setInfo();
                  }
                }}>
                <View>
                  <Text>{MapPowerResult.get(item.powerStr)}</Text>
                  <Text style={style.remark}>{item.powerStr}</Text>
                </View>
              </TouchableOpacity>
            </ListItem>
          ))}
        </View>
      ))}

      <View style={style.group}>
        <View style={[style.item, style.itemNoBorder]}>
          <Text></Text>
          <Text></Text>
        </View>
      </View>
    </ScrollView>
  );
};
